package com.qf.course.core.entity;

import java.lang.reflect.Field;

/**
 * 通用的ToString方法 - 反射实现
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class BaseToString {

    @Override
    public String toString() {
        Class<? extends BaseToString> cls = this.getClass();
        Field[] declaredFields = cls.getDeclaredFields();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (Field field : declaredFields) {
            field.setAccessible(true);

            if (stringBuilder.length() != 1) {
                stringBuilder.append(",");
            }

            String name = field.getName();
            Object value = null;
            try {
                value = field.get(this);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            stringBuilder.append(name + "=" + value);
        }
        stringBuilder.append("]");

        return stringBuilder.toString();
    }
}
